package com.cvte.boe.media.utils;

import android.content.Context;
import android.os.SystemClock;


import com.cvte.boe.media.model.ExtraInfoModel;
import com.cvte.boe.media.model.LocalDeviceInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenyunzhou on 2015/9/16.
 */
public class MountAction implements Runnable {

    List<String> mWaitingQueue = new ArrayList<>();
    private Context mContext = null;
    private boolean isMounting = false;
    boolean isStop = false;
    private Object mLock = new Object();

    public MountAction(Context context) {
        mContext = context;
    }

    public void addMount(String mountPath) {
        if (mountPath != null && mountPath.startsWith("file://")) {
            mountPath = mountPath.substring("file://".length());
        }
        synchronized (mWaitingQueue) {
            if (!mWaitingQueue.contains(mountPath)) {
                mWaitingQueue.add(mountPath);
            }
        }
    }

    private String getFirst() {
        synchronized (mWaitingQueue) {
            if (!mWaitingQueue.isEmpty()) {
                String path = mWaitingQueue.get(0);
                mWaitingQueue.remove(0);
                return path;
            }
        }
        return null;
    }

    @Override
    public void run() {
        while (!isStop) {
            if (mWaitingQueue.isEmpty()) {
                SystemClock.sleep(0x64);
                continue;
            }
            if (mountListener != null) {
                mountListener.onMountStart();
            }
            synchronized (mLock) {
                isMounting = true;
                String path = getFirst();
                if (path != null) {
                    MountListUtil.getInstance().initMountInfoList();
                    LocalDeviceInfo dto = DeviceDataUtils.getDeviceFromCmdDetail(path);
                    if (dto != null) {
                        ExtraInfoModel model = MountListUtil.getInstance().getExtraInfoModel(path);
                        dto.setDevAlias(model != null ? model.getLabel() : "");
                        DeviceDataUtils.getLocDevSizeByStatFs(mContext, dto);
                        DeviceDataUtils.getLocDevName(dto);
                        if (mountListener != null) {
                            isMounting = false;
                            mountListener.onMountComplete(dto);
                            continue;
                        }
                    }
                }
                isMounting = false;
            }
        }
    }

    public void stop() {
        isStop = true;
    }

    public boolean isMounting() {
        return isMounting;
    }

    public interface MountListener {
        void onMountComplete(LocalDeviceInfo info);

        void onMountStart();
    }

    public static MountListener mountListener = null;

    public void setMountListener(MountListener listener) {
        mountListener = listener;
    }

}
